﻿namespace Sgr.Utilities
{
    public static class CollectionSyncHelper
    {
        /// <summary>
        /// 通用集合差异更新方法
        /// </summary>
        public static void SyncCollection<TEntity, TKey>(
            List<TEntity> collection,
            IEnumerable<TKey> newKeys,
            Func<TKey, TEntity> createFunc,
            Func<TEntity, TKey> keySelector)
        {
            var currentKeys = new HashSet<TKey>(collection.Select(keySelector));
            var newKeySet = new HashSet<TKey>(newKeys);

            // 删除不再需要的实体
            var keysToRemove = currentKeys.Except(newKeySet);
            collection.RemoveAll(e => keysToRemove.Contains(keySelector(e)));

            // 添加新的实体
            var keysToAdd = newKeySet.Except(currentKeys);
            foreach (var key in keysToAdd)
            {
                collection.Add(createFunc(key));
            }
        }
    }
}